﻿using Newtonsoft.Json;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.S.Database.Write.Api
{
    /// <summary>
    /// NuGet引用： Qiniu(8.3.1)
    /// 七牛云存储官网：  https://www.qiniu.com/products/kodo
    /// 七牛云存储空间管理：  https://portal.qiniu.com/kodo/bucket   !!!!! 切记：设置为：公开空间
    /// c#参考官网文档：  https://developer.qiniu.com/kodo/1237/csharp   /  https://developer.qiniu.com/kodo/1500/csharp-sdk-v7p0
    /// </summary>
    public class QiNiuHelper
    {
        /// <summary>
        /// NuGet引用： Qiniu(8.3.1)
        /// 七牛云上传节流数据
        /// </summary>
        public async static Task<UploadQiNiuResult> QiniuUploadFile(string ak, string sk, string Bucket, string BaseUrl, string filePath, Stream st)
        {
            ////保存到七牛云上的文件目录
            //string saveKey = "Images/zizhiImg/66.jpg"; //注意: /
            //// 本地文件路径
            //string filePath = AppDomain.CurrentDomain.BaseDirectory + "images\\66.jpg";  // 注意: //
            ////byte[] data = System.IO.File.ReadAllBytes("D:/QFL/1.mp3");
            //byte[] data = File.ReadAllBytes(filePath);

            // 设置上传策略
            PutPolicy putPolicy = new QiNiuHelper().SetPutPolicy();

            // 生成上传token
            Mac mac = new Mac(ak, sk);
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            // 设置上传区域
            Config config = new QiNiuHelper().SetConfigZone();

            // 表单上传
            FormUploader target = new FormUploader(config);
            HttpResult result = target.UploadStream(st, Bucket, token, null);
            Console.WriteLine("返回结果： " + result.ToString());

            var imgUrl = BaseUrl + Bucket;
            return new UploadQiNiuResult
            {
                Url = imgUrl,
                Success = true,
            };
        }
        /// <summary>
        /// 设置上传策略
        /// </summary>
        /// <returns></returns>
        public PutPolicy SetPutPolicy()
        {
            PutPolicy putPolicy = new PutPolicy();

            // 设置要上传的目标空间
            putPolicy.Scope = "dys666";

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;

            // 上传策略有效期(对应于生成的凭证的有效期，单位:秒)
            putPolicy.SetExpires(3600);

            // 设置返回策略，避免 download token not specified 错误
            putPolicy.ReturnBody = "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"fsize\":$(fsize),\"bucket\":\"$(bucket)\",\"name\":\"$(fname)\"}";

            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 100;

            return putPolicy;
        }
        /// <summary>
        /// 设置上传区域
        /// </summary>
        /// <returns></returns>
        public Config SetConfigZone()
        {
            Config config = new Config();

            // 设置上传区域  [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
            config.Zone = Zone.ZONE_CN_North;

            // 设置 http 或者 https 上传
            config.UseHttps = true;
            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U512K;

            return config;
        }
    }
}
